package com.bilibili.movies.controller;

import com.bilibili.movies.entity.User;
import com.bilibili.movies.entity.UserCollection;
import com.bilibili.movies.service.UserCollectionServiceImpl;
import com.bilibili.movies.service.UserService;
import com.bilibili.movies.util.EmailUtils;
import com.bilibili.movies.util.JWTUtils;
import com.bilibili.movies.util.MD5Utils;
import com.bilibili.movies.util.Result;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.time.LocalDate;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class Controller {
    @Resource
    UserService userService;
    @Resource
    EmailUtils email;
    @Resource
    UserCollectionServiceImpl collectionService;
    @Resource
    RedisTemplate<String,Object> redisTemplate;

   @GetMapping("/GetEmailCode")
    public Result register(@RequestParam String QQemail) throws MessagingException, UnsupportedEncodingException {



       String s = email.sendMessage(QQemail);
        redisTemplate.opsForValue().set(QQemail,s,60, TimeUnit.SECONDS);


       return Result.suceess("发送成功");
    }

    @PostMapping("/register")
    public Object register(@RequestBody User user,HttpServletRequest request){


        if( redisTemplate.opsForValue().get(user.getEmail()).equals(user.getCode())){
            User one = userService.lambdaQuery().eq(User::getEmail,user.getEmail()).one();
            if(one!=null){
                return Result.error("账户已经存在");
            }else{
                user.setPassword(MD5Utils.encode(user.getPassword()));
                userService.save(user);

                return Result.suceess("注册成功");
                }
        }else {
            return Result.error("验证码错误");
        }


        }



    @PostMapping("/login")
    public Object login(@RequestBody User user){
        user.setPassword(MD5Utils.encode(user.getPassword()));
        User one = userService.lambdaQuery().eq(User::getEmail, user.getEmail())
                .eq(User::getPassword, user.getPassword()).one();
        if(one==null){
            return Result.error("邮箱号或者密码错误");
        }else{
            //将用户收藏查出来缓存到redis中
            List<UserCollection> list = collectionService.lambdaQuery().eq(UserCollection::getUserId, one.getId()).orderByDesc(UserCollection::getTime).list();
            redisTemplate.opsForValue().set(String.valueOf(one.getId()),list);

            return Result.suceess(JWTUtils.setJWT(one));
        }

    }
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody User user){
        System.out.println("user=="+user);
       if (user.getPassword()==null||user.getPassword()==""){
           if(user.getNickName()==null||user.getNickName()==""){
               return Result.suceess("修改成功");
           }else{
               User one = userService.lambdaQuery().eq(User::getId, user.getId()).one();
               one.setNickName(user.getNickName());
               System.out.println("one+++===="+one);
               userService.updateById(one);

               return Result.suceess("修改成功");
           }
       }else{
           if(user.getNickName()!=null&&user.getNickName()!=""){
               userService.updateById(user);
               return Result.suceess("修改成功");
           }else{
               User one = userService.lambdaQuery().eq(User::getId, user.getId()).one();
               one.setNickName(user.getNickName());
               one.setPassword(user.getPassword());
               userService.updateById(one);
               return Result.suceess("修改成功");
           }

       }


    }
    @GetMapping("/getlist")
    public Object get(HttpServletRequest request){
       String token=request.getHeader("Authorization");
        System.out.println("here::"+token);
        return  Result.error(token);

    }
    @GetMapping("/isCollection")

    public Result isCollection(Integer userId,Integer movieId){


        List<UserCollection> collectionList = (List<UserCollection>) redisTemplate.opsForValue().get(String.valueOf(userId));

        if(collectionList==null){
            return Result.suceess(0);
        }

        for (UserCollection userCollection : collectionList) {

            if(movieId.equals(userCollection.getMovieId())){

                return  Result.suceess(1);
            }
        }
        return Result.suceess(0);
    }
    @PostMapping ("/collection")
    public Result controll(@RequestBody UserCollection userCollection){

       if(userCollection.getFlag()==1){//取消收藏
        collectionService.Delete(userCollection);
        //删除redis缓存，并且重新更新
           List<UserCollection> collectionList = (List<UserCollection>) redisTemplate.opsForValue().get(String.valueOf(userCollection.getUserId()));
           collectionList.removeIf(movie->movie.getMovieId()==userCollection.getMovieId());
           redisTemplate.opsForValue().set(String.valueOf(userCollection.getUserId()),collectionList);
           return  Result.suceess(0);
       }else{//收藏
           userCollection.setTime(LocalDate.now());
           collectionService.save(userCollection);
           //删除redis缓存，并且重新更新
           List<UserCollection> collectionList = (List<UserCollection>) redisTemplate.opsForValue().get(String.valueOf(userCollection.getUserId()));
           if(collectionList==null){
               redisTemplate.opsForValue().set(String.valueOf(userCollection.getUserId()),userCollection);
           }else{
               collectionList.add(userCollection);
               redisTemplate.opsForValue().set(String.valueOf(userCollection.getUserId()),collectionList);
           }
           return Result.suceess(1);

       }


    }
    @GetMapping("/getCollection")//controller得到用户收藏信息（缓存）
    public Result getCollection(Integer id){
       String Id=String.valueOf(id);
        List<UserCollection> list = (List<UserCollection>) redisTemplate.opsForValue().get(Id);

        return Result.suceess(list);
    }

}
